//
//  Date.swift
//
//  Created by 李加建 on 2021/9/7.
//

import Foundation

public extension Date {
    func toString(_ dateFormat: String = "yyyy-MM-dd HH:mm:ss") -> String? {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "zh_CN")
        formatter.dateFormat = dateFormat
        let string = formatter.string(from: self)
        return string
    }
}

public extension Date {
    func timeAgo() -> String? {
        let time = Int(timeIntervalSinceNow)
        if time > 0 {
            // 未来的时间
            return toString("yyyy-MM-dd HH:mm:ss")
        } else {
            // 过去的时间
            let ago = -time
            if ago < 60 {
                return "刚刚"
            } else if ago < 86400 {
                let hour = ago / 3600
                return "\(hour)小时前"
            } else {
                return toString("MM-dd HH:mm")
            }
        }
    }
}
